//
//  RegisterTableViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/15.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import TextFieldEffects
import PKHUD
import Alamofire
import SwiftyJSON

private let smsTimerInterval: TimeInterval = 60

class RegisterTableViewController: UITableViewController {

  // MARK: - IBOutlets
  
  @IBOutlet private weak var phoneTextField: HoshiTextField!
  @IBOutlet private weak var codeTextField: HoshiTextField!
  @IBOutlet private weak var emailTextField: HoshiTextField!
  @IBOutlet private weak var nicknameTextField: HoshiTextField!
  @IBOutlet private weak var passwordTextField: HoshiTextField!
  @IBOutlet private weak var confirmPasswordTextField: HoshiTextField!
  @IBOutlet private weak var genderSegmentedControl: UISegmentedControl!
  @IBOutlet private weak var avatarButton: UIButton!
  @IBOutlet private weak var smsButton: UIButton!
  
  // MARK: - Private vars
  
  private var smsTimer: Timer?
  private var smsCountDown: TimeInterval = 0
  
  private var avatarImage: UIImage?
  private var currentFocusedTextField: UITextField?
  
  // MARK: - Private methods
  
  private func prepareUI() {
    tableView.backgroundColor = .clear
    avatarButton.clipsToBounds = true
    avatarButton.layer.cornerRadius = 32
  }
  
  private func restoreFirstResponder() {
    if currentFocusedTextField != nil {
      _ = currentFocusedTextField!.becomeFirstResponder()
    }
  }
  
  private func showImagePicker(sourceType: UIImagePickerController.SourceType) {
    
    let picker = UIImagePickerController()
    picker.view.tintColor = UIColor(fromPreeset: .globalTint)
    picker.delegate = self
    picker.allowsEditing = true
    picker.sourceType = sourceType
    
    picker.navigationBar.tintColor = UIColor(fromPreeset: .globalTint)
    picker.navigationBar.barTintColor = UIColor(fromPreeset: .navBarTint)
    picker.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(fromPreeset: .navTitleColor)]
    picker.navigationBar.isTranslucent = false
    
    present(picker, animated: true)
  }
  
  private func getGenderValue() -> Int {
    if genderSegmentedControl.selectedSegmentIndex == 0 {
      return User.Gender.female.rawValue
    } else if genderSegmentedControl.selectedSegmentIndex == 1 {
      return User.Gender.male.rawValue
    } else {
      return User.Gender.unknown.rawValue
    }
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    prepareUI()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  @IBAction func requestSMSCode() {
    guard let phone = phoneTextField.text?.trim(),
      phone.isValidChineseCellPhoneNumber() else {
        let alert = UIAlertController(title: "手机号不正确", message: "请重新输入", cancelTitle: "确定") { _ in
          self.phoneTextField.becomeFirstResponder()
        }
        present(alert, animated: true)
        return
    }
    
    HUD.show(.labeledProgress(title: "请稍后", subtitle: nil))
    let body = ["cell_phone": phone]
    API.shared.requestAPI(APIURLStrings.requestSMS, method: .post, body: body, successCallback: { json in
      HUD.flash(.labeledSuccess(title: "验证码已发送", subtitle: "请查收短信"), delay: 1.5)
      if let code = json["sms"].string {
        self.codeTextField.text = code
      }
      self.view.endEditing(true)
      
      self.smsTimer?.invalidate()
      self.smsCountDown = smsTimerInterval
      self.smsButton.isEnabled = false
      self.smsTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
        if self.smsCountDown > 0 {
          self.smsButton.setTitle("\(Int(self.smsCountDown))s", for: .normal)
          self.smsCountDown -= 1
        } else {
          timer.invalidate()
          self.smsButton.setTitle("获取验证码", for: .normal)
          self.smsButton.isEnabled = true
        }
      })
    }) { message, code in
      HUD.flash(.labeledError(title: "请求失败", subtitle: "请重试"), delay: 1.5)
    }
  }
  
  @IBAction func addAvatar() {
    if UIImagePickerController.isSourceTypeAvailable(.camera) {
      //show a actrionSheet to choose photo library or camera
      let alert = UIAlertController(title: "头像来源", message: nil, preferredStyle: .actionSheet)
      alert.view.tintColor = UIColor(fromPreeset: .globalTint)
      let cameraAction = UIAlertAction(title: "相机", style: .default, handler: { _ in
        self.showImagePicker(sourceType: .camera)
      })
      let cameraRollAction = UIAlertAction(title: "照片库", style: .default, handler: { _ in
        self.showImagePicker(sourceType: .photoLibrary)
      })
      let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
      
      alert.addAction(cameraAction)
      alert.addAction(cameraRollAction)
      alert.addAction(cancelAction)
      
      present(alert, animated: true)
    } else {
      showImagePicker(sourceType: .photoLibrary)
    }
  }
  
  @IBAction func register() {
    func presentAlert(title: String, message: String? = nil, completion: @escaping () -> Void) {
      let alert = UIAlertController(title: title, message: message, cancelTitle: "确定") { _ in
        completion()
      }
      present(alert, animated: true)
    }
    
    guard let phone = phoneTextField.text?.trim(),
      phone.isValidChineseCellPhoneNumber() else {
        presentAlert(title: "手机号不正确", message: "请重新输入") {
          self.phoneTextField.becomeFirstResponder()
        }
        return
    }
    
    guard let code = codeTextField.text?.trim(),
      code.count == 6 else {
        presentAlert(title: "验证码不正确", message: "请重新输入") {
          self.codeTextField.becomeFirstResponder()
        }
        return
    }
    
    guard let email = emailTextField.text?.trim(),
      email.isValidEmail() else {
        presentAlert(title: "Email不正确", message: "请重新输入") {
          self.emailTextField.becomeFirstResponder()
        }
        return
    }
    
    guard let nickname = nicknameTextField.text?.trim(),
      nickname.trim().count > 0 else {
        presentAlert(title: "昵称不能为空", message: "请重新输入") {
          self.nicknameTextField.becomeFirstResponder()
        }
        return
    }
    
    guard let password = passwordTextField.text,
      password.count > 0 else {
        presentAlert(title: "密码不能为空", message: "请重新输入") {
          self.passwordTextField.becomeFirstResponder()
        }
        return
    }
    
    guard let confirmPassword = confirmPasswordTextField.text,
      confirmPassword.count > 0 else {
        presentAlert(title: "请再次输入密码", message: "") {
          self.confirmPasswordTextField.becomeFirstResponder()
        }
        return
    }
    
    guard confirmPassword == password else {
        presentAlert(title: "两次密码输入不一致", message: "请重新输入") {
          self.passwordTextField.becomeFirstResponder()
        }
        return
    }
    
    guard let image = avatarImage,
      let imageData = image.pngData() else {
        presentAlert(title: "请添加头像", message: "") {
          self.view.endEditing(true)
          self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
          self.currentFocusedTextField = nil
        }
        return
    }
    
    let genderValue = getGenderValue()
    
    let deviceUUID = DeviceInfo.current.appUUID
    let iosVersion = DeviceInfo.current.iosVersion
    let modelName = DeviceInfo.current.modelName
    let body = [
      "listener[cell_phone]": phone,
      "listener[code]": code,
      "listener[email]": email,
      "listener[gender]": genderValue,
      "listener[display_name]": nickname,
      "listener[password_digest]": password.md5HexString(),
      "listener[device[identifier]]": deviceUUID,
      "listener[device[os]]": iosVersion,
      "listener[device[model]]": modelName
      ] as [String : Any]
    
    let avatarData: UploadData? = (
      avatarImage != nil ?
        UploadData (
          data: imageData,
          key: "listener[avatar]",
          fileName: "avatar.png",
          mimeType: .image
        ) : nil
    )
    
    HUD.show(.labeledProgress(title: "请稍后", subtitle: nil))
    API.shared.upload(APIURLStrings.systemRegister, parameters: body, uploadData: avatarData, successCallback: { json in
      loggingPrint(json)
      let listenerJSON = json["listener"]
      var gender = User.Gender.unknown
      if let responseGender = User.Gender(rawValue: listenerJSON["gender"].intValue) {
        gender = responseGender
      }
      let user = User (
        identifier: listenerJSON["id"].intValue,
        cellPhone: listenerJSON["cell_phone"].stringValue,
        loginType: User.LoginType.system,
        nickname: listenerJSON["display_name"].stringValue,
        avatar: RemoteImage(dictionary: listenerJSON["avatar"].dictionaryObject!),
        token: json["token"].stringValue,
        gender: gender,
        loginDate: Date(),
        email: listenerJSON["email"].string
      )
      UserManager.shared.currentUser = user
      HUD.flash(.labeledSuccess(title: "用户注册成功", subtitle: nil), delay: 1.5)
      if let nav = self.navigationController as? BaseNavigationController {
        if nav.isPresentedModally {
          nav.dismissDelegate?.dismiss(navigationController: nav, completion: nil)
        }
        NotificationCenter.default.post(name: .currentUserUpdated, object: nil)
      }
    }) { (message, code) in
      HUD.hide()
      let alert = UIAlertController(title: message, message: "请重试", cancelTitle: "确定", cancelHandler: nil)
      self.present(alert, animated: true)
    }
  }
}

// MARK: - UITextFieldDelegate

extension RegisterTableViewController: UITextFieldDelegate {
  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    if textField == emailTextField {
      nicknameTextField.becomeFirstResponder()
    } else if textField == nicknameTextField {
      passwordTextField.becomeFirstResponder()
    } else if textField == passwordTextField {
      confirmPasswordTextField.becomeFirstResponder()
    } else if textField == confirmPasswordTextField {
      view.endEditing(true)
    }
    return true
  }
  
  func textFieldDidBeginEditing(_ textField: UITextField) {
    currentFocusedTextField = textField
  }
}

// MARK: - UIImagePickerControllerDelegate

extension RegisterTableViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
  
  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)

    var image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.editedImage)] as? UIImage
    if image == nil {
      image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage
    }
    if image != nil {
      UIGraphicsBeginImageContext(CGSize(width: 500.0, height: 500.0))
      image!.draw(in: CGRect(x: 0, y: 0, width: 500.0, height: 500.0))
      avatarImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      
      if let image = avatarImage {
        dismiss(animated: true, completion: {
          DispatchQueue.main.async {
            self.avatarButton.setImage(image, for: .normal)
            self.restoreFirstResponder()
          }
        })
      }
    }
  }
  
  func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true) {
      self.restoreFirstResponder()
    }
  }
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
	return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
	return input.rawValue
}
